<?php
use entities\IM_Model;
use entities\IM_Model_stats;
use entities\IM_Model_picture;

class IM_C_ManageModelPictures
	extends BaseController{
	
	public function	start(){
		fw_util_custom_doLoginCheck();
		$this->registry->template->arr_jsScriptUrls = $this->arr_appConf['js_files'];
		$this->registry->template->arr_cssSriptUrls = $this->arr_appConf['css_style_sheets'];
		$this->getSubNavi();
		$this->registry->template->show('Admin-ManageModelPictures.php');
	}
	
	public function editPics(){
		//$this->registry->template->arr_jsScriptUrls = $this->arr_appConf['js_files'];
		//$this->registry->template->arr_cssSriptUrls = $this->arr_appConf['css_style_sheets'];
		//$this->registry->template->show('Admin-ManageModelPictures.php');
	}
	
	public function setModelToEdit(){
		$i_modelId = $_GET['ident'];
		//$i_modelId = EncryptionHandler::get()->doDecrypt($i_modelId);
		$_SESSION['modToEdit'] = $i_modelId;
		if(!file_exists(C_FW_ABSPATH.'/im_images_mod/pictures/im_model&'.$i_modelId) && !file_exists(C_FW_ABSPATH.'/im_images_mod/thumbnails/im_model&'.$i_modelId)){
			mkdir(C_FW_ABSPATH.'/im_images_mod/pictures/im_model&'.$i_modelId, 0777);
			mkdir(C_FW_ABSPATH.'/im_images_mod/thumbnails/im_model&'.$i_modelId, 0777);
		}
		
		fw_util_redirect('AdminManageModelPictures');
	}
	
	public function doSetDefaultPicture(){
		$i_modelId = EncryptionHandler::get()->doDecrypt($_SESSION['modToEdit']);
		$o_modelPic = $this->o_em->getRepository('entities\IM_Model_picture')->findOneBy(array(
			'id_mod' => $i_modelId, 
			'fileName'=> $_POST['file']
		));
		
		$o_model = $this->o_em->find('entities\IM_Model', (int)$i_modelId);
		
		$o_model->setCoverPhotoId($o_modelPic->getId());
		
		$this->o_em->merge($o_model);
		$this->o_em->flush();
	}
	
	public function getDefaultModelPicture(){
		$i_modelId = EncryptionHandler::get()->doDecrypt($_SESSION['modToEdit']);
		$o_model = $this->o_em->find('entities\IM_Model', (int)$i_modelId);
		
		$o_modelCoverPic = $this->o_em->find('entities\IM_Model_picture', $o_model->getCoverPhotoId());
		if($o_modelCoverPic != null){
			fw_util_outputJson(array('file'=>$o_modelCoverPic->getFileName()));
		}
	}
	
	public function manageCoverPhoto(){
		$this->registry->template->arr_jsScriptUrls = $this->arr_appConf['js_files'];
		$this->registry->template->arr_cssSriptUrls = $this->arr_appConf['css_style_sheets'];
		$this->getSubNavi();
		
		$this->registry->template->s_mainAppDisplay = $this->getModelPicsTable();
		
		$this->registry->template->show('Admin-ManageModels.php');
	}
	
	private function getModelPicsTable(){
		$s_viewModelsTableHtml = '<table id="model-pictures-table">';
		
		$s_viewModelsTableHtml .= '<thead>';
		$s_viewModelsTableHtml .= '<tr>';
		$s_viewModelsTableHtml .= '<th>id</th>';
		$s_viewModelsTableHtml .= '<th>picture</th>';
		$s_viewModelsTableHtml .= '<th>file name</th>';
		$s_viewModelsTableHtml .= '<th>date updated</th>';
		//actions
		$s_viewModelsTableHtml .= '<th>set as cover picture?</th>';
		//end actions
		$s_viewModelsTableHtml .= '</tr>';
		$s_viewModelsTableHtml .= '</thead>';
		$s_viewModelsTableHtml .= '<tr><td colspan="5" class="dataTables_empty">Loading data from server</td></tr>';
		
		$s_viewModelsTableHtml .= '</tbody>';
		
		$s_viewModelsTableHtml .= '</table>';
		
		return $s_viewModelsTableHtml;
	}
	
	
	public function doModelsPicsTableAction()
	{
		if($_SERVER['REQUEST_METHOD'] == 'GET'){
			$arr_request = $_GET;
		}else{
			$arr_request = $_POST;
		}
		
		//pagination
		if(isset($arr_request['iDisplayStart']) && isset($arr_request['iDisplayLength'])){
			//offset of displayed records
			$this->setOffset($arr_request['iDisplayStart']);
	
			//max amount of records to display
			$this->setMaxShown($arr_request['iDisplayLength']);
				
			//order by, sorting
			
			$i_modelId = EncryptionHandler::get()->doDecrypt($arr_request['ident']);
			$this->arr_currPageObjects = $this->o_em->getRepository('entities\IM_Model_picture')->getModelPicsByPage(
				$this->getOffset(),
				$this->getMaxShown(),
				$arr_request['iSortCol_0'],
				$arr_request['sSortDir_0'],
				intval($arr_request['sEcho']),
				$arr_request['sSearch'],
				$i_modelId
			);
			fw_util_outputJson($this->arr_currPageObjects);
		}
	}
	
	private function setOffset($i_offset = 0)
	{
		if(trim($i_offset) != ''){
			if(is_numeric($i_offset)){
				$this->i_offset = (int)htmlspecialchars($i_offset);
			}
		}
	}
	
	private function setMaxShown($i_maxShown = 10)
	{
		if(trim($i_maxShown) != ''){
			if(is_numeric($i_maxShown)){
				$this->i_maxShown = (int)htmlspecialchars($i_maxShown);
			}
		}
	}
	
	private function getOffset()
	{
		return $this->i_offset;
	}
	
	private function getMaxShown()
	{
		return $this->i_maxShown;
	}
	
	
	
	
	public function runMultiFileUpload(){
		/*
		 * jQuery File Upload Plugin PHP Example 5.7
		 * https://github.com/blueimp/jQuery-File-Upload
		 *
		 * Copyright 2010, Sebastian Tschan
		 * https://blueimp.net
		 *
		 * Licensed under the MIT license:
		 * http://www.opensource.org/licenses/MIT
		 */
		
		//error_reporting(E_ALL | E_STRICT);
		
		if($_SESSION['modToEdit'] != ''){
			$s_relPath = 'im_model&' . $_SESSION['modToEdit'];
			require(C_FW_fwPackage. 'libraries/jqueryFileUpload/php/' . 'upload.class.php');
			$arr_options = array(
				'script_url'=> fw_util_getFullUrl(). '/AdminShowModelPictures/runMultiFileUpload', 
				'upload_dir'=> C_FW_ABSPATH.'/im_images_mod/pictures/' . $s_relPath . '/',
				'upload_url'=> C_FW_TRUEURL.'im_images_mod/pictures/' . $s_relPath . '/',
		 		'image_versions' => array(
					'thumbnail' => array(
						'upload_dir' => C_FW_ABSPATH.'/im_images_mod/thumbnails/' . $s_relPath . '/',
						'upload_url' => C_FW_TRUEURL.'im_images_mod/thumbnails/' . $s_relPath . '/',
						'max_width' => 452,
						'max_height' => 452
					)
				)
			);
			
			$upload_handler = new UploadHandler($arr_options);
			
			switch ($_SERVER['REQUEST_METHOD']) {
			    case 'OPTIONS':
			        break;
			    case 'HEAD':
			    case 'GET':
			        $upload_handler->get();
			        break;
			    case 'POST':
			        if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
			            $upload_handler->delete();
			        } else {
			           	$upload_handler->post();
			            //print_r($arr_picInfo);
			            $arr_picInfo = $upload_handler->getCurrPicInfo();
			            $this->managePictureDbPersist($arr_picInfo, $s_relPath);
			        }
			        break;
			    case 'DELETE':
			        $upload_handler->delete();
			        $s_fileName = $upload_handler->getCurrFileNameForDelete();
			        $this->removePictureFromDb($s_fileName);
			        break;
			    default:
			        header('HTTP/1.1 405 Method Not Allowed');
			}
		}		
	}
	
	private function removePictureFromDb($s_fileName){
		$i_modelId = EncryptionHandler::get()->doDecrypt($_SESSION['modToEdit']);
		$o_modelPic = $this->o_em->getRepository('entities\IM_Model_picture')->findOneBy(array(
			'id_mod' => $i_modelId, 
			'fileName'=> $s_fileName
		));
		
		try {
			$this->o_em->remove($o_modelPic);
			$this->o_em->flush();
		} catch (Exception $e) {
			$this->o_em->remove($o_modelPic);
			$this->o_em->flush();
		}
	}
	
	private function managePictureDbPersist($arr_picInfo, $s_relPath){
		$o_file = $arr_picInfo[0];
		$i_modelId = EncryptionHandler::get()->doDecrypt($_SESSION['modToEdit']);
		
		$o_modelPic = new entities\IM_Model_picture();
		$o_modelPic->setFileName($o_file->name);
		$o_modelPic->setModelId($i_modelId);
		$o_modelPic->setRelPath($s_relPath);
		$o_modelPic->setThumbId($o_file->name);
		$o_modelPic->setUpdateDate(new \DateTime("now"));
		
		$this->o_em->persist($o_modelPic);
		$this->o_em->flush();
	}
	
}